<template>
  <div class="el-breadcrumb flex align-items-center docs-breadcrumb">
    <span
      v-for="item in breadcrumb"
      :key="item.key"
      class="el-breadcrumb__item flex align-items-center"
    >
      <span v-if="item.err" class="el-breadcrumb__inner nowrap">{{ item.label }}</span>
      <router-link v-else :to="item.path" class="el-breadcrumb__inner is-link">
        {{ item.label }}
      </router-link>
      <span class="el-breadcrumb__separator">/</span>
    </span>
    <slot></slot>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  name: 'breadcrumb', // 资源路径（仅在全部分类下，不在精品分类中显示）
  data() {
    return {
      breadcrumb: [],
    };
  },
  computed: {
    folderId() { return this.$route.params.folderId; },
  },
  created() {
    this.initBreadcrumb();
  },
  methods: {
    ...mapActions({
      setCurFolder: 'setCurrentFolder',
    }),
    async initBreadcrumb() {
      const resetQuery = Object.assign({}, this.$route.query, {
        page: undefined,
      });
      const itemPath = { path: this.$route.path, query: resetQuery };

      if (!this.folderId) this.breadcrumb = [{ path: itemPath, label: '根目录', key: 0 }];
      else {
        const parentPath = await this.initParentPath();
        // 将 'id-title/id-title' 转换成 [{ id: xx, title: xx }, { id: xx, title: xx }] 的形式
        const parentObjs = parentPath.split('/').map(itemStr => ({
          id: itemStr.substring(0, itemStr.indexOf('-')),
          title: itemStr.substring(itemStr.indexOf('-') + 1) || '根目录',
        }));
        const folderBaseUrl = `/spaces/${this.$route.params.spaceId}/resources`;
        this.breadcrumb = parentObjs.map(item => ({
          key: item.id,
          path: { path: `${folderBaseUrl}/${item.id}`, query: resetQuery },
          label: item.title,
        }));
      }
    },
    initParentPath() {
      return new Promise((resolve, reject) => {
        this.$api.spaceResources.show({
          spaceId: this.$route.params.spaceId,
          docId: this.folderId,
          type: 'ProductFolder',
        }).then(res => resolve(`${res.data.parent_path || ''}/${res.data.id}-${res.data.title}`))
          .catch(() => reject(''));
      });
    },
    // 给父组件调用，上传当前文件面包屑
    uploadFolderBreadcrumb() {
      const curFolder = this.breadcrumb[this.breadcrumb.length - 1] || {};
      const displayPath = this.breadcrumb.map(i => i.label).join('/');
      const obj = {
        id: curFolder.key,
        displayPath,
      };
      this.setCurFolder(obj);
    },
  },
  watch: {
    folderId() { this.initBreadcrumb(); },
  },
};
</script>

<style lang="scss">
.docs-breadcrumb .el-breadcrumb__inner.is-link{
  font-weight: normal;
  color: #2e2e2e;
  &:hover {
    text-decoration: underline;
  }
}
.docs-breadcrumb .el-breadcrumb__separator {
  color: #5e5e5e;
  font-weight: normal;
  margin: 0 .3rem;
}
</style>
